package com.jetpackframework.skin;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;

import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;

public class SkinLayoutInflaterFactory implements LayoutInflater.Factory2 , Observer {
    private static String[] mClassPrefixList = {
            "android.widget.",
            "android.webkit.",
            "android.app.",
            "android.view."
    };
    private static Class[] mConstructorSignature = {Context.class,AttributeSet.class};
    private Map<String,Constructor<? extends View>> constructorMap = new HashMap<>();
    private SkinAttributeSets attrs;
    public SkinLayoutInflaterFactory(){
        attrs = new SkinAttributeSets();
    }

    @Override
    public View onCreateView(String s, Context context, AttributeSet attrs) {
        return null;
    }

    @Override
    public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
        View view = createSDKView(name, context, attrs);
        if (view == null){
            view = createView(name, context, attrs);
        }
        if (view != null){
            Log.e("TAG--", "view="+view);
            this.attrs.look(view,attrs);
        }
        return view;
    }

    private View createView(String qualityName, Context context, AttributeSet attrs) {
        Constructor constructor = findConstructor(context, qualityName);
        try {
            return (View) constructor.newInstance(context, attrs);
        } catch (Exception e) {

        }
        return null;
    }



    private View createSDKView(String name, Context context, AttributeSet attrs) {
        if (name == null){
            return null;
        }
        if (-1 != name.indexOf(".")) {
            return null;
        }
        for (String prefix : mClassPrefixList){
            View view = createView(prefix + name,context,attrs);
            if (view != null){
                return view;
            }
        }
        return null;
    }
    private Constructor<? extends View> findConstructor(Context context, String qualityName) {
        Constructor<? extends View> constructor = constructorMap.get(qualityName);
        if (constructor == null){
            try {
                Class<? extends View> viewClass = context.getClassLoader().loadClass(qualityName).asSubclass(View.class);
                Constructor<? extends View> viewClassConstructor = viewClass.getConstructor(mConstructorSignature);
                constructorMap.put(qualityName,viewClassConstructor);
                return viewClassConstructor;
            } catch (Exception e) {

            }
        }
        return null;
    }

    @Override
    public void update(Observable o, Object arg) {
        attrs.skinApply();
    }
}
